package com.javaee.interceptor.Utils;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 监听器
 * @auther 龚诗浩
 */
public class LoginListener implements HttpSessionListener {

    //创建session时触发
    public void sessionCreated(HttpSessionEvent se) {
        //获取servlet上下文对象
        ServletContext servletContext = se.getSession().getServletContext();

        Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
        if (onlineCount==null){
            //如果在线人数为0，则设置在线人数为1
            onlineCount = 1;
        }else {
            //在线人数+1
            int count = onlineCount;
            onlineCount= count + 1;
        }
        //将在线人数放入servletContext对象中
        servletContext.setAttribute("OnlineCount",onlineCount);

    }
    //销毁session时触发
    public void sessionDestroyed(HttpSessionEvent se) {
        //获取servlet上下文对象
        ServletContext servletContext = se.getSession().getServletContext();

        Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
        if (onlineCount==null){
            //如果在线人数为0，则设置在线人数为0
            onlineCount = 0;
        }else {
            //在线人数-1
            int count = onlineCount;
            onlineCount= count - 1;
        }
    }
}
